using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class BackpackOperation : MonoBehaviour
{
	public Transform parentGrid;
	//BoxCollider[] colliders;
	BackpackItem[] backItems;
	public Dictionary<int,BackpackItem> backPackItemDic = new Dictionary<int, BackpackItem> ();
	BackpackItem targetItem;
	
	void Awake ()
	{
		//colliders = parentGrid.GetComponentsInChildren<BoxCollider> ();
		backItems = parentGrid.GetComponentsInChildren<BackpackItem> ();
		
		for (int i = 0; i < backItems.Length; i++) {
			string parentName = backItems [i].transform.parent.name;
			int parentIndex = int.Parse (parentName.Substring (parentName.Length - 1));
			
			string mName = backItems [i].transform.name;
			int mIndex = int.Parse (mName.Substring (mName.Length - 1)) - 1;
				
			int tIndex = parentIndex * 9 + mIndex;
			backItems [i].index = tIndex;
			
			backPackItemDic.Add (tIndex, backItems [i]);
		}
		
		SendMessageTOServer ();
		
		MySocket.getInstance ().addEventListener ((int)SystemMsgFlag.NetMessageSC.NM_SC_BAG_OPEN_ACK, ListenToServer);
		
		MySocket.getInstance ().addEventListener ((int)SystemMsgFlag.NetMessageSC.NM_SC_BAG_ITEM_TO_EQUIPMENT_ACK, BackItemToEquip);
		MySocket.getInstance ().addEventListener ((int)SystemMsgFlag.NetMessageSC.NM_SC_BAG_ITEM_ADD_ACK, ExchangeItem);
		MySocket.getInstance ().addEventListener ((int)SystemMsgFlag.NetMessageSC.NM_SC_BAG_ITEM_DROP_ACK, DeleteItem);
		MySocket.getInstance ().addEventListener ((int)SystemMsgFlag.NetMessageSC.NM_SC_BAG_SLOT_OPEN_MONEY_ACK, UnLockItemMoney);
		MySocket.getInstance ().addEventListener ((int)SystemMsgFlag.NetMessageSC.NM_SC_BAG_SLOT_OPEN_ACK, UnLockItems);
		
		MySocket.getInstance ().addEventListener ((int)SystemMsgFlag.NetMessageSC.NM_SC_BAG_ITEM_TO_WAREHOUSE_ACK, BackItemToWarehouse);
		MySocket.getInstance ().addEventListener ((int)SystemMsgFlag.NetMessageSC.NM_SC_BAG_ITEM_INFO_ACK, PopTipsWindow);
	}
	
	void SendMessageTOServer ()
	{
		ByteArrayEx byteArray = new ByteArrayEx ();
		byteArray.writeInt ((int)SystemMsgFlag.NetMessageCS.NM_CS_BAG_OPEN_SYN);
		MySocket.getInstance ().Async_Send (byteArray.byteArray);
	}
	
	void ListenToServer (System.Object getter, DispatchEventArgs e)
	{
		
		ByteArrayEx byteArray = new ByteArrayEx (e.data [0] as byte[]);
		
		//处理数据//
		int backpackFieldCount = (int)byteArray.readByte ();
		
		for (int i = 0; i < backpackFieldCount; i++) {
			BackpackItem backItem = backPackItemDic [i];
			UILabel countLabel = backItem.countLabel;
			UISprite goodSprite = backItem.icon;
			UISprite bgSprite = backItem.iconBG;
			
			countLabel.enabled = true;
			goodSprite.enabled = true;
			bgSprite.enabled = true;
			
			byte itemType = byteArray.readByte ();
			int itemId = byteArray.readInt ();
			int itemCount = byteArray.readInt ();
			//格子为空//
			if (itemType == (byte)GameDefine.GameObjectType.GAMEOBJECT_UNKONW) {
				countLabel.enabled = false;
				goodSprite.enabled = false;
				bgSprite.enabled = false;
			} else {
				if (itemCount == 1 || itemCount == 0) {
					countLabel.enabled = false;
				}
			}
			
			backItem.myItem = new Item (itemType, itemId, itemCount, goodSprite.enabled);
			backItem.icon.spriteName = backItem.myItem.SpriteName;
			backItem.iconBG.spriteName = backItem.myItem.BgSpriteName;
			
			if(backItem.myItem.BgSpriteName == "") backItem.iconBG.enabled = false;
			
			backItem.icon.MakePixelPerfect();
			backItem.iconBG.MakePixelPerfect();
			
			countLabel.text = itemCount.ToString ();
		}
		
		UIManagement.Instance ().SetVisiable (gameObject, GameDefine.VISIABLE);
	}
	
	/// <summary>
	/// 将物品放到仓库里//
	/// </summary>
	void BackItemToWarehouse (System.Object getter, DispatchEventArgs e)
	{
		ByteArrayEx byteArray = new ByteArrayEx (e.data [0] as byte[]);
		
		byte result = byteArray.readByte ();
		
		if (result == (byte)CustomToClientFlag.RequestResult.success) {
			if (targetItem) {
				if(targetItem.targetItem != null){
					targetItem.myItem.Exchange (targetItem.targetItem.myItem);
				
					targetItem.targetItem.Refresh ();
					targetItem.Refresh ();
					
				} else {
					int index = (int)byteArray.readByte ();
					
					GameObject warehouseWindow = UIManagement.Instance().GetWindow("Window_Warehouse");
					
					if(warehouseWindow != null){
						WarehouseOperation operation = warehouseWindow.GetComponent<WarehouseOperation>();
						
						if(operation != null){
							BackpackItem item =  operation.backPackItemDic[index];
							
							targetItem.myItem.Exchange (item.myItem);
					
							item.Refresh ();
							targetItem.Refresh ();
						}
					}
				}
			}
		} else {
			//targetItem.targetItem = null;
			targetItem.targetItem.Refresh ();
			targetItem.Refresh ();
		}
		
		if(targetItem.targetItem != null)
			targetItem.targetItem = null;
		
		Cursor.Clear ();
		
		targetItem.canDrop = false;
	}
	
	/// <summary>
	/// 将物品放到人物身上//
	/// </summary>
	void BackItemToEquip (System.Object getter, DispatchEventArgs e)
	{
		ByteArrayEx byteArray = new ByteArrayEx (e.data [0] as byte[]);
		
		byte result = byteArray.readByte ();
		
		if (result == (byte)CustomToClientFlag.RequestResult.success) {
			
			if (targetItem) {
				
				if(targetItem.targetItem != null){
					targetItem.myItem.Exchange (targetItem.targetItem.myItem);
					
					targetItem.targetItem.Refresh ();
					targetItem.Refresh ();
					
				} else {
					string equipPos = SqliteReader.getInstance ().getIniVal ("Equip", "EquipID", 
						targetItem.myItem.ItemID.ToString(), new string[]{"Position"})[0];
					int equipIndex = int.Parse(equipPos) - 1;
					
					GameObject roleInfoWindow = UIManagement.Instance().GetWindow("Window_Role");
					
					if(roleInfoWindow != null){
						RoleInfoWindowOperation operation = roleInfoWindow.GetComponent<RoleInfoWindowOperation>();
						
						if(operation != null){
							BackpackItem item =  operation.backPackItemDic[equipIndex];
							
							targetItem.myItem.Exchange (item.myItem);
					
							item.Refresh ();
							targetItem.Refresh ();
						}
					}
				}
			}
		} else {
			//targetItem.targetItem = null;
			if(targetItem.targetItem != null)
				targetItem.targetItem.Refresh ();
			targetItem.Refresh ();
		} 
		
		if(targetItem.targetItem != null)
			targetItem.targetItem = null;
		
		Cursor.Clear ();
		
		targetItem.canDrop = false;
	}
	
	/// <summary>
	/// 叠加或者交换物品//
	/// </summary>
	void ExchangeItem (System.Object getter, DispatchEventArgs e)
	{
		ByteArrayEx byteArray = new ByteArrayEx (e.data [0] as byte[]);
		
		byte result = byteArray.readByte ();
		
		if (result == (byte)CustomToClientFlag.RequestResult.success) {
			
			if (targetItem) {
				targetItem.myItem.Exchange (targetItem.targetItem.myItem);
				
				targetItem.targetItem.Refresh ();
				targetItem.Refresh ();
			}
		} else {
			
		}
		
		Cursor.Clear ();
		targetItem.icon.enabled = targetItem.myItem.Visible;
		targetItem.iconBG.enabled = targetItem.myItem.Visible;
		
		if(targetItem.targetItem != null)
			targetItem.targetItem = null;
		
		targetItem.canDrop = false;
	}
	
	//删除背包物品返回//
	void DeleteItem (System.Object getter, DispatchEventArgs e)
	{
		
		ByteArrayEx byteArray = new ByteArrayEx (e.data [0] as byte[]);
		
		byte result = byteArray.readByte ();
		
		if (result == (byte)CustomToClientFlag.RequestResult.success) {
			targetItem.myItem.Visible = false;
			
			targetItem.Refresh ();
		}
		
		Cursor.Clear ();
		targetItem.icon.enabled = targetItem.myItem.Visible;
		targetItem.iconBG.enabled = targetItem.myItem.Visible;
		
		targetItem.canDrop = false;
	}
	
	//解锁背包格子钱数请求//
	void UnLockItemMoney (System.Object getter, DispatchEventArgs e)
	{
		ByteArrayEx byteArray = new ByteArrayEx (e.data [0] as byte[]);
		
		byte result = byteArray.readByte ();
		
		if (result == (byte)CustomToClientFlag.RequestResult.success) {
			int money = (int)byteArray.readUnsignedShort ();
			byte itemCount = byteArray.readByte ();
			
			UIManagement.Instance ().OpenPopUpWindow ("String_Prompt_open_package", UnLockItemConfirm, null, new object[]{(object)money,(object)itemCount});
		} else {
			
		}
	}
	
	//解锁背包格子返回//
	void UnLockItems (System.Object getter, DispatchEventArgs e)
	{
		ByteArrayEx byteArray = new ByteArrayEx (e.data [0] as byte[]);
		
		byte result = byteArray.readByte ();
		
		if (result == (byte)CustomToClientFlag.RequestResult.success) {
			for (int i = 0; i <= targetItem.index; i++) {
				BackpackItem t_item = backPackItemDic [i];
				if (t_item.myItem.Locked == GameDefine.ITEMLOCKED) {
					t_item.myItem.Locked = GameDefine.ITEMUNLOCKED;
					t_item.myItem.Visible = GameDefine.INVISIABLE;
					
					t_item.Refresh ();
				}
			}
		} else {
			
		}
	}
	
	//开启背包/仓库格子//
	void UnLockItemRequest (BackpackItem item)
	{
		//开启背包//
		ByteArrayEx byteArray = new ByteArrayEx ();
		byteArray.writeInt ((int)SystemMsgFlag.NetMessageCS.NM_CS_BAG_SLOT_OPEN_MONEY_SYN);
		byteArray.writeByte ((byte)item.index);
		MySocket.getInstance ().Async_Send (byteArray.byteArray);
		
		targetItem = item;
	}
	
	//删除物品请求//
	void DeleteItemRequest (BackpackItem item)
	{
		targetItem = item;
		DeleteItemOperation();
	}
	
	void DeleteItemOperation(){
		UIManagement.Instance ().OpenPopUpWindow ("String_Prompt_discarded", ClickConfirm, ClickCancel);
	}
	
	//移动物品或者换装//
	void MoveOrEquipRequest (BackpackItem item)
	{
		targetItem = item;
		//区分装备还是背包物品//
		if (item.targetItem.storageState == BackpackItem.StorageStateType.RoleInfo) {
			EquipEquipment();
		} else if (item.targetItem.storageState == BackpackItem.StorageStateType.Backpack) {
			MoveItem();
		} else if(item.targetItem.storageState == BackpackItem.StorageStateType.Warehouse){
			MoveItemToWarehouse();
		}
	}
	
	//装备物品//
	void EquipEquipment(){
		ByteArrayEx byteArray = new ByteArrayEx ();
		byteArray.writeInt ((int)SystemMsgFlag.NetMessageCS.NM_CS_BAG_ITEM_TO_EQUIPMENT_SYN);
		byteArray.writeByte ((byte)targetItem.index);
		if(targetItem.targetItem != null){
			byteArray.writeByte ((byte)targetItem.targetItem.index);
		} else {
			string equipPos = SqliteReader.getInstance ().getIniVal ("Equip", "EquipID", 
				targetItem.myItem.ItemID.ToString(), new string[]{"Position"})[0];
			int equipIndex = int.Parse(equipPos) - 1;
			byteArray.writeByte ((byte)equipIndex);
		}
		
		MySocket.getInstance ().Async_Send (byteArray.byteArray);
	}
	
	//移动物品到仓库//
	void MoveItemToWarehouse(){
		ByteArrayEx byteArray = new ByteArrayEx ();
		byteArray.writeInt ((int)SystemMsgFlag.NetMessageCS.NM_CS_BAG_ITEM_TO_WAREHOUSE_SYN);
		if(targetItem.targetItem != null){
			//移动到仓库//
			int type = 0;
			byteArray.writeByte ((byte)type);
			byteArray.writeByte ((byte)targetItem.index);
			byteArray.writeByte ((byte)targetItem.targetItem.index);
		} else {
			int type = 1;
			byteArray.writeByte ((byte)type);
			byteArray.writeByte ((byte)targetItem.index);
		}
		
		MySocket.getInstance ().Async_Send (byteArray.byteArray);
	}
	
	void MoveItem(){
		ByteArrayEx byteArray = new ByteArrayEx ();
		byteArray.writeInt ((int)SystemMsgFlag.NetMessageCS.NM_CS_BAG_ITEM_ADD_SYN);
		byteArray.writeByte ((byte)targetItem.index);
		byteArray.writeByte ((byte)targetItem.targetItem.index);
		MySocket.getInstance ().Async_Send (byteArray.byteArray);
	}
	
	//删除物品确认//
	void ClickConfirm ()
	{
		ByteArrayEx byteArray = new ByteArrayEx ();
		byteArray.writeInt ((int)SystemMsgFlag.NetMessageCS.NM_CS_BAG_ITEM_DROP_SYN);
		byteArray.writeByte ((byte)targetItem.index);
		MySocket.getInstance ().Async_Send (byteArray.byteArray);
		
		targetItem.canDrop = false;
	}
	
	//删除物品取消//
	void ClickCancel ()
	{
		targetItem.icon.enabled = targetItem.myItem.Visible;
		targetItem.iconBG.enabled = targetItem.myItem.Visible;
		
		targetItem.canDrop = false;
	}
	
	//解锁背包格子确认//
	void UnLockItemConfirm ()
	{
		ByteArrayEx byteArray = new ByteArrayEx ();
		byteArray.writeInt ((int)SystemMsgFlag.NetMessageCS.NM_CS_BAG_SLOT_OPEN_SYN);
		byteArray.writeByte ((byte)targetItem.index);
		MySocket.getInstance ().Async_Send (byteArray.byteArray);
	}
	
	//Tips弹窗请求//
	void PopTipsWindowRequest (BackpackItem item)
	{
		ByteArrayEx byteArray = new ByteArrayEx ();
		byteArray.writeInt ((int)SystemMsgFlag.NetMessageCS.NM_CS_BAG_ITEM_INFO_SYN);
		byteArray.writeByte ((byte)item.index);
		MySocket.getInstance ().Async_Send (byteArray.byteArray);
		
		targetItem = item;
	}
	
	//Tips弹窗//
	void PopTipsWindow (System.Object getter, DispatchEventArgs e)
	{
		ByteArrayEx byteArray = new ByteArrayEx (e.data [0] as byte[]);
		
		byte itemType = byteArray.readByte();
		int itemId = byteArray.readInt();
	
		if (itemType == (byte)GameDefine.GameObjectType.GAMEOBJECT_ITEM) {
			//弹物品Tips//
		} else if (itemType == (byte)GameDefine.GameObjectType.GAMEOBJECT_EQUIP) {
			//弹装备Tips//
			Hashtable tipsTable = new Hashtable ();
			string[] equipProperties = SqliteReader.getInstance ().getIniVal ("Equip", "EquipID", itemId.ToString(), new string[]{"Name","Profession","LvLimit"});
			string titleName = BinaryReaderTool.getInstance ().getSwfLangStr (equipProperties [0]);
			string iconSpriteName = targetItem.icon.spriteName;
			tipsTable.Add ("TitleName", titleName);
			tipsTable.Add ("SpriteName", iconSpriteName);
			tipsTable.Add ("EquipProfession", equipProperties [1]);
			tipsTable.Add ("LvLimit", equipProperties [2]);
			Vector3 pos = targetItem.transform.position;
			tipsTable.Add ("EquipPosition", pos);
			
			if(UIManagement.Instance().CheckWindowExits("Window_Role")){
				string leftStr = BinaryReaderTool.getInstance ().getSwfLangStr ("String_loading");
				string rightStr = BinaryReaderTool.getInstance ().getSwfLangStr ("String_discarded");
				UIManagement.Instance ().OpenEquipTipsWindow (tipsTable,EquipEquipment,DeleteItemOperation,leftStr,rightStr);
			} else if(UIManagement.Instance().CheckWindowExits("Window_Warehouse")){
				string leftStr = BinaryReaderTool.getInstance ().getSwfLangStr ("String_deposited");
				string rightStr = BinaryReaderTool.getInstance ().getSwfLangStr ("String_discarded");
				UIManagement.Instance ().OpenEquipTipsWindow (tipsTable,MoveItemToWarehouse,DeleteItemOperation,leftStr,rightStr);
			} else {
				string rightStr = BinaryReaderTool.getInstance ().getSwfLangStr ("String_discarded");
				UIManagement.Instance ().OpenEquipTipsWindow (tipsTable,null,DeleteItemOperation,null,rightStr);
			}
		}
	}
	
	//整理请求//
	void ArrangeRequest(){
		ByteArrayEx byteArray = new ByteArrayEx ();
		byteArray.writeInt ((int)SystemMsgFlag.NetMessageCS.NM_CS_BAG_SETTLE_SYN);
		MySocket.getInstance ().Async_Send (byteArray.byteArray);
	}
	
	void OnDestroy ()
	{
		//colliders = null;
		MySocket.getInstance ().removeEventListener ((int)SystemMsgFlag.NetMessageSC.NM_SC_BAG_OPEN_ACK);
		
		MySocket.getInstance ().removeEventListener ((int)SystemMsgFlag.NetMessageSC.NM_SC_BAG_ITEM_TO_EQUIPMENT_ACK);
		MySocket.getInstance ().removeEventListener ((int)SystemMsgFlag.NetMessageSC.NM_SC_BAG_ITEM_ADD_ACK);
		MySocket.getInstance ().removeEventListener ((int)SystemMsgFlag.NetMessageSC.NM_SC_BAG_ITEM_DROP_ACK);
		MySocket.getInstance ().removeEventListener ((int)SystemMsgFlag.NetMessageSC.NM_SC_BAG_SLOT_OPEN_MONEY_ACK);
		MySocket.getInstance ().removeEventListener ((int)SystemMsgFlag.NetMessageSC.NM_SC_BAG_SLOT_OPEN_ACK);
		
		MySocket.getInstance ().removeEventListener ((int)SystemMsgFlag.NetMessageSC.NM_SC_BAG_ITEM_INFO_ACK);
		
		backPackItemDic.Clear ();
	}
}
